<template>
  <div class="attractions-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>乡村旅游景点</span>
          <el-button type="primary" @click="handleAdd">上架景点</el-button>
        </div>
      </template>

      <el-table :data="attractionList" style="width: 100%" v-loading="loading">
        <el-table-column label="景点图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.avatar || defaultImage"
              :preview-src-list="row.avatar ? [row.avatar] : []"
              fit="cover"
              class="attraction-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="景点名称" />
        <el-table-column
          prop="description"
          label="景点描述"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="门票价格" width="100">
          <template #default="{ row }"> ¥{{ row.price }} </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="120">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(row)"
              >下架</el-button
            >
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="还没有上架旅游景点" :image-size="200">
            <el-button type="primary" @click="handleAdd">立即上架</el-button>
          </el-empty>
        </template>
      </el-table>
    </el-card>

    <!-- 添加/编辑景点对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="景点名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入景点名称" />
        </el-form-item>

        <el-form-item label="景点描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入景点描述"
          />
        </el-form-item>

        <el-form-item label="景点类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择景点类型">
            <el-option
              v-for="option in typeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="门票价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :precision="2"
            :step="10"
          />
        </el-form-item>

        <el-form-item label="景点图片" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :http-request="customUpload"
            :show-file-list="false"
            accept="image/jpeg,image/png"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Picture } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

// 景点列表数据
const attractionList = ref([]);

// 获取景点类型名称
const getTypeName = (type: number) => {
  const typeMap: { [key: number]: string } = {
    1: "农家体验",
    2: "休闲度假",
    3: "农家乐",
  };
  return typeMap[type] || "其他";
};

// 获取类型标签样式
const getTypeTag = (type: number) => {
  const tagMap: { [key: number]: string } = {
    1: "success",
    2: "warning",
    3: "info",
  };
  return tagMap[type] || "";
};

// 获取景点列表
const getAttractionList = async () => {
  try {
    const res = await request({
      url: "/touristAttractions/queryRuralTourist",
      method: "get",
    });
    if (res.success) {
      attractionList.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取景点列表失败");
  }
};

// 组件挂载时获取数据
onMounted(() => {
  getAttractionList();
});

const dialogVisible = ref(false);
const dialogTitle = ref("上架景点");
const formRef = ref<FormInstance>();

const formData = reactive({
  name: "",
  description: "",
  type: 1,
  price: 0,
  avatar: "",
  id: undefined,
  productType: 1,
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入景点名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入景点描述", trigger: "blur" }],
  type: [{ required: true, message: "请选择景点类型", trigger: "change" }],
  price: [{ required: true, message: "请输入门票价格", trigger: "blur" }],
});

// 是否是编辑模式
const isEdit = ref(false);

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  dialogTitle.value = "添加景点";
  // 重置表单数据
  formData.name = "";
  formData.description = "";
  formData.type = 1;
  formData.price = 0;
  formData.avatar = "";
  formData.productType = 1;
  formData.id = undefined; // 添加 id 字段
};

// 自定义上传方法
const customUpload = async (options: any) => {
  const uploadFormData = new FormData();
  uploadFormData.append("uploadFile", options.file);

  try {
    const res = await request({
      url: "/file/ali/upload",
      method: "post",
      data: uploadFormData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (res.success) {
      formData.avatar = res.data;
      ElMessage.success("图片上传成功");
    }
  } catch (error) {
    ElMessage.error("图片上传失败");
    options.onError(error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = isEdit.value
          ? "/touristAttractions/updateInfo"
          : "/touristAttractions/add";
        const res = await request({
          url,
          method: "post",
          data: {
            id: formData.id,
            name: formData.name,
            description: formData.description,
            type: formData.type,
            price: formData.price,
            avatar: formData.avatar,
            productType: formData.productType,
          },
        });

        if (res.success) {
          ElMessage.success(isEdit.value ? "编辑成功" : "添加成功");
          dialogVisible.value = false;
          getAttractionList(); // 刷新列表
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? "编辑失败" : "添加失败");
      }
    }
  });
};

// 关闭对话框时重置表单
const handleClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
};

// 编辑景点
const handleEdit = (row: any) => {
  isEdit.value = true;
  dialogVisible.value = true;
  dialogTitle.value = "编辑景点";
  // 填充表单数据
  formData.id = row.id;
  formData.name = row.name;
  formData.description = row.description;
  formData.type = row.type;
  formData.price = row.price;
  formData.avatar = row.avatar;
  formData.productType = row.productType || 1;
};

// 下架景点
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要下架景点"${row.name}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await request({
          url: "/touristAttractions/down",
          method: "post",
          data: {
            id: row.id,
          },
        });

        if (res.success) {
          ElMessage.success("下架成功");
          getAttractionList(); // 刷新列表
        }
      } catch (error) {
        ElMessage.error("下架失败");
      }
    })
    .catch(() => {
      // 取消下架操作，不做任何处理
    });
};

// 默认图片
const defaultImage = "src/assets/default-attraction.png"; // 你可以替换成实际的默认图片路径

// 景点类型选项
const typeOptions = [
  { label: "农家体验", value: 1 },
  { label: "休闲度假", value: 2 },
  { label: "农家乐", value: 3 },
];

// 添加 loading 状态
const loading = ref(false);
</script>

<style scoped>
.attractions-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.attraction-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

:deep(.el-empty) {
  padding: 40px 0;
}

:deep(.el-empty) .el-empty__description {
  margin-top: 20px;
  font-size: 14px;
  color: #909399;
}

:deep(.el-empty) .el-button {
  margin-top: 20px;
}
</style> 